import { observable, action } from 'mobx';
import { WeaForm, WeaTableNew } from 'comsMobx';
import { ValidateForm } from './util';
import * as Api from '../../apis/setting/labelManage';

const { TableStore } = WeaTableNew;
const initalState = {
  editTitle: '',
  editFields: [],
  isEdit: false,
  editId: '',
};
export default class LabelStore {
  @observable labelTable = new TableStore();
  @observable editForm = new WeaForm();
  @observable editTitle = initalState.editTitle;
  @observable editFields = initalState.editFields;
  @observable isEdit = initalState.isEdit;
  @observable editId = initalState.editId;

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  @action clear = () => this.setStoreState(initalState);

  @action getMailLabel = (params, initPage = false) => {
    Api.getMailLabel(params).then((res) => {
      initPage
        ? this.labelTable.getDatas(res.sessionkey)
        : this.labelTable.getDatas(res.sessionkey, 1);
    });
  };

  @action operateUserMailLabel = async (params) => {
    let res = await Api.operateUserMailLabel(params);
    return res;
  };

  @action getEmailLabelCondition = (params, callback) => {
    Api.getEmailLabelCondition(params).then((res) => {
      this.editForm.initFormFields(res.conditioninfo);
      this.editFields = res.conditioninfo || [];
      if (callback) callback();
    });
  };

  @action editSubmit = (callback) => {
    ValidateForm(this.editForm, callback);
  };

  @action getMailLabelBean = (params) => {
    Api.getMailLabelBean(params).then((res) => {
      let formParams = this.editForm.getFormParams();
      for (let attr in formParams) {
        if (Object.prototype.hasOwnProperty.call(res.emailLabelBean, attr)) {
          this.editForm.updateFields({
            [attr]: { value: res.emailLabelBean[attr] },
          });
        }
      }
    });
  };
}
